package com.study.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.study.pojo.FileProperty;


@Controller
public class downloadController {
	
	@Value("#{settings.webServer}")
	private String webPath;
	
	//获取目录下所有文件名称
	@RequestMapping("listFile")
	public String listFile(Model model, HttpServletRequest request, HttpServletResponse response){
		
		List<FileProperty> listFile = new ArrayList<>();
		String path = request.getServletContext().getRealPath("/")+"uploadFiles";
		
		File dir = new File(path);
		
		if(!dir.exists()){
			return "fail";
		}
		File[] file = dir.listFiles();
		for(int i=0; i<file.length; i++){
			File temp = file[i];
			
			FileProperty fileProperty = new FileProperty();
			fileProperty.setName(temp.getName());
			fileProperty.setPath(webPath+"/uploadFiles/"+temp.getName());
			if(temp.isDirectory()){
				fileProperty.setType("directory");
			} else if(temp.isFile()){
				fileProperty.setType("file");
			}
			listFile.add(fileProperty);
		}
		model.addAttribute("listFile",listFile);
		return "download";
	}
	
	//下载文件的后台处理方式
	@RequestMapping("downloadFile")
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String fileName = request.getParameter("fileName");
		System.out.println(fileName);
		
        //在上传路径中找对应的文件
		String path = request.getServletContext().getRealPath("/")+"uploadFiles";
		File dir = new File(path);
		File[] file = dir.listFiles();
		
		File getFile = null;
		
		for(int i=0; i<file.length; i++){
			if(file[i].getName().equals(fileName)){
				 getFile = file[i];
				 break;
			}
		}
		if(getFile == null){
			request.setAttribute("message", "您要下载的资源已被删除！！");
			request.getRequestDispatcher("/WEB-INF/jsp/fail.jsp").forward(request, response);
			return;
		} else {
			//1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
	        response.setContentType("multipart/form-data");  
	        //2.设置文件头：最后一个参数是设置下载文件名(如a.txt)  
	        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
	        //读取要下载的文件，保存到文件输入流
	        FileInputStream in = new FileInputStream(getFile);
	        //创建输出流
	        OutputStream out = response.getOutputStream();
	        //创建缓冲区
	        byte buffer[] = new byte[512];
	        int len = 0;
	        //循环将输入流中的内容读取到缓冲区当中
	        while((len=in.read(buffer))>0){
		        //输出缓冲区的内容到浏览器，实现文件下载
		        out.write(buffer, 0, len);
	        }
	        //关闭文件输入流
	        in.close();
	        //关闭输出流
	        out.flush();
	        out.close();
	        }
		}
}
